//
//  NetworkTools.swift
//  weibo
//
//  Created by 陈勇 on 16/2/26.
//  Copyright © 2016年 chenyong. All rights reserved.
//

import UIKit
import AFNetworking

enum CZRequestMethod: String {

    case GET = "GET"
    case POST = "POST"

}

class NetworkTools: AFHTTPSessionManager {
    
    let appkey = "1762557123"
    let appSecret = "94cd8bd8bc074a724d1f5cc3406a3dd1"
    let redirectUri = "http://www.baidu.com"
    
    static let sharedTools: NetworkTools = {
    
        let tools = NetworkTools(baseURL: nil)
        
        //设置 AFN 的网络请求超时
        tools.requestSerializer.timeoutInterval = 15
        
        // 设置反序列化支持数据格式
        tools.responseSerializer.acceptableContentTypes?.insert("text/plain")
        
        // 将 JSON 中的 NULL 值过滤，有些第三方框架在做字典转模型时，如果遇到 NULL 值会崩溃！
        (tools.responseSerializer as! AFJSONResponseSerializer).removesKeysWithNullValues = true
        // 启动连接状态监听 - 通过通知中心发布的
        tools.reachabilityManager.startMonitoring()
        
        return tools
    
    }()
    
    deinit {
        // 停止连接状态监听
        reachabilityManager.stopMonitoring()
    }
    
    /// 判断当前网络是否能够连接
    var reachable: Bool {
        return reachabilityManager.reachable
    }
    
    func request(method: CZRequestMethod, URLString: String, parameters: [String: AnyObject]?, finished: (result: [String: AnyObject]?)->()) {
        
        let success = { (task: NSURLSessionDataTask, responseObject: AnyObject?)-> Void in
            
            if let result = responseObject as? [String: AnyObject]{
            
                finished(result: result)
            
            }else{
            
            print("数据格式错误")
                finished(result: nil)
        }
    }
        let failure = { (task: NSURLSessionDataTask?, error: NSError) -> Void in
        
            print("网络请求错误 \(error)")
            finished(result: nil)
        }
        
        if method == .GET{
            //GET请求
            GET(URLString, parameters: parameters, progress: nil, success: success, failure: failure)
        }else{
            //POST请求
            POST(URLString, parameters: parameters,progress: nil, success: success, failure: failure)
        }
    }
    //
    func upload(URLString: String, parameters: [String: AnyObject]?, data: NSData, name: String, finished:(result: [String: AnyObject]?) -> ()) {
    
    //   data 要上传到服务器的二进制数据
    //   name 服务器指定上传数据的 `字段名`，在开发的时候，一定要咨询后台或者查阅文档，新浪微博 pic
    //    fileName 保存在服务器上的文件名，目前大多数公司的服务器接口，`文件名可以随便值`，后台接口会自动生成文件名
    //    后台接口，在接收到上传图片后，会生成缩略图／中等尺寸图／大图／原图
    //    mimeType 告诉服务器上传二进制数据的类型，与 contentType 等价
    //    格式：
    
    POST(URLString, parameters: parameters, constructingBodyWithBlock: { (formData) -> Void in
        //拼接上传的二进制数据
        formData.appendPartWithFileData(data, name: name, fileName: "helloworld", mimeType: "application/octet-stream")

        }, progress: nil, success: { (_, responseObject) -> Void in
            
            if let result = responseObject as? [String: AnyObject] {
                finished(result: result)
            } else {
                
                print("数据格式错误")
                finished(result: nil)
            }
            
        }) { (_, error) -> Void in
            
            print("网络请求错误 \(error)")
            finished(result: nil)

        }
    }
}